/***Load the settings from external file with fstream
    Copyright (C) 2012  Davide Moriello

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. 
	
	Contact me for help or more info: davidemo89@gmail.com       ****/
#include <fstream>
#include <iostream>
#include <cstring>
#include "settings.h"

using namespace std;


void initSettings(settings &sett)
{
	sett = new settings_node;

	sett->lifebeforeteleport = NULL;
	sett->nexus = NULL;
	sett->lifebeforesoundalert = -1;
	sett->preventionTeleport = NULL;

	getSettings(sett);
		
}

void getSettings(settings &sett)
{
	fstream fileopen;
	char tmp[80];
	

	fileopen.open("settings.ini",ios::in);

	if(!fileopen.is_open()){
		printErrorSettings(sett);
		sett->done = false;
		return;
	}

	fileopen >> tmp;
	while(!fileopen.eof()){

		if(strcmp(tmp,"nexus") == 0){
			fileopen >> tmp; // = 
			fileopen >> tmp; //Value			
			sett->nexus = tmp[0];			
		}else if(strcmp(tmp,"lifebeforeteleport") == 0){
			fileopen >> tmp; // = 
			fileopen >> tmp; //Value			
			sett->lifebeforeteleport = atoi(tmp);
		}else if(strcmp(tmp,"preventiveTeleport") == 0){
			fileopen >> tmp; // = 
			fileopen >> tmp; //Value			
			sett->preventionTeleport = atoi(tmp);
		}else if(strcmp(tmp,"lifeBeforeSoundAlert") == 0){
			fileopen >> tmp; // = 
			fileopen >> tmp; //Value	
			sett->lifebeforesoundalert =  atoi(tmp);
		}

		fileopen >> tmp;
			
		
	}

	//If no value is set, get default
	if(sett->nexus == NULL)
		sett->nexus = 'C';
	if(sett->lifebeforeteleport == NULL)
		sett->lifebeforeteleport = 20;
	if(sett->preventionTeleport == -1)
		sett->preventionTeleport = 1;
	if(sett->lifebeforeteleport > 90)
		sett->lifebeforeteleport = 90;
	if(sett->lifebeforesoundalert == NULL)
		sett->lifebeforesoundalert = 0;

	sett->done = true;
	return;

}

void printErrorSettings(settings& sett)
{
	//Default value if error in loading the ini
	cout << "Loading settings.ini error\n";	
	cout << "Loading default settings:" << endl;
	sett->nexus = 'C';
	sett->lifebeforeteleport = 20;
	sett->preventionTeleport = 1;
	sett->lifebeforesoundalert = 0;
}